package assignment1.eventplan.request;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class RequestEngine {

    private static class SingleInstanceHolder {
        static final RequestEngine engine = new RequestEngine(10);
    }

    public static RequestEngine get() {
        return SingleInstanceHolder.engine;
    }


    private final AtomicInteger mSequenceGenerator = new AtomicInteger();

    private final ExecutorService mNetworkService;
    private ResponseDelivery delivery;

    private RequestEngine(int threadSize) {
        this(threadSize, new Handler(Looper.getMainLooper()));
    }

    private RequestEngine(int threadSize, Handler handler) {
        delivery = new ResponseDelivery(handler);
        mNetworkService = Executors.newFixedThreadPool(threadSize);
    }

    public void request(Request request) {
        request.setSequence(mSequenceGenerator.incrementAndGet());
        mNetworkService.execute(new RequestTask(delivery, request));
    }

    private static class RequestTask implements Runnable {

        private final Request request;
        private final ResponseDelivery delivery;

        RequestTask(ResponseDelivery delivery, Request request) {
            this.request = request;
            this.delivery = delivery;
        }

        @Override
        public void run() {
            final Request request = this.request;
            if (!request.isCancel()) {
                Log.d("request", "start->" + System.currentTimeMillis());

                BufferedReader reader = null;
                try {
                    URL url = new URL(request.getUrl());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod(request.getMethod());

                    InputStream stream = connection.getInputStream();

                    Response response = new Response();
                    response.code = connection.getResponseCode();
                    response.message = connection.getResponseMessage();

                    InputStreamReader input = new InputStreamReader(stream);
                    reader = new BufferedReader(input);
                    char[] buffer = new char[1024];
                    StringBuilder builder = new StringBuilder();
                    while (reader.read(buffer, 0, 1024) != -1) {
                        builder.append(buffer);
                    }
                    connection.disconnect();
                    response.data = builder.toString();
                    Log.d("request", "post-result->" + System.currentTimeMillis());
                    delivery.postResponse(request, response);

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != reader) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }else {
                Log.d("request", "cancel->" + System.currentTimeMillis());
            }
        }
    }
}
